﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using Word = Microsoft.Office.Interop.Word;
using System.Text;
using System.Linq.Expressions;
using System.IO;

public partial class Manage_StatQuestion : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            #region 绑定年、月、日
            for (int i = 2012; i <= 2007 + 10 || i <= DateTime.Now.Year + 2; i++)
            {
                Year1.Items.Add(new ListItem(Convert.ToString(i), Convert.ToString(i)));
                Year2.Items.Add(new ListItem(Convert.ToString(i), Convert.ToString(i)));
            }
            for (int i = 1; i <= 12; i++)
            {
                Month1.Items.Add(new ListItem(Convert.ToString(i), Convert.ToString(i)));
                Month2.Items.Add(new ListItem(Convert.ToString(i), Convert.ToString(i)));
            }
            for (int i = 1; i <= 31; i++)
            {
                Day1.Items.Add(new ListItem(Convert.ToString(i), Convert.ToString(i)));
                Day2.Items.Add(new ListItem(Convert.ToString(i), Convert.ToString(i)));
            }

            Year2.SelectedValue = Convert.ToString(DateTime.Now.Year);
            Month2.SelectedValue = Convert.ToString(DateTime.Now.Month);
            Day2.SelectedValue = Convert.ToString(DateTime.Now.Day);
            #endregion

            #region 加载单位信息
            XmlDataSource xds = new XmlDataSource();
            xds.DataFile = Toolkit.GetRealDataFilePath("Department.xml");
            xds.XPath = "//District";

            Districts.DataSource = xds;
            Districts.DataTextField = "name";
            Districts.DataValueField = "name";
            Districts.DataBind();
            #endregion
        }
    }
    protected void Export_Click(object sender, EventArgs e)
    {
        DateTime st = DateTime.Parse(string.Format("{0}年{1}月{2}日", Year1.SelectedValue, Month1.SelectedValue, Day1.SelectedValue));
        DateTime ed = DateTime.Parse(string.Format("{0}年{1}月{2}日", Year2.SelectedValue, Month2.SelectedValue, Day2.SelectedValue));

        Word.Application app = null;
        Word.Document doc = null;

        object ms = Type.Missing;

        try
        {
            StringBuilder sb = new StringBuilder();
            #region 获取选中的县区信息
            foreach (ListItem li in Districts.Items)
            {
                if (li.Selected)
                {
                    sb.Append((sb.Length == 0 ? "" : " ") + li.Value);
                }
            }
            #endregion

            CmsDataContext db = new CmsDataContext();
            var q = from aQ in db.Question
                    orderby aQ.Time descending, aQ.Title
                    select aQ;

            #region 查询条件
            Expression<Func<Question, bool>> lmbda = PredicateBuilder<Question>.CreatePredicate(new string[] { "Country" }, sb.ToString().Trim(), "aA");
            var p = q.Where(lmbda);
            #endregion

            string path = Toolkit.MappingPath(Toolkit.PathOfTemporary);
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            string file = Toolkit.NextUUID + ".doc";
            File.Copy(Toolkit.MappingPath(string.Format("{0}/{1}", Toolkit.PathOfReport, Toolkit.TemplateOfStatQuestionDetail)), string.Format("{0}/{1}", path, file));

            app = new Word.Application();
            doc = app.Documents.Open(string.Format("{0}/{1}", path, file));

            Word.Bookmark bm = doc.Bookmarks["Time"];
            bm.Range.Text = string.Format("{0:yyyy年MM月dd日}", DateTime.Now);

            bm = doc.Bookmarks["Person"];
            bm.Range.Text = Toolkit.CurrentUserName;

            bm = doc.Bookmarks["During"];
            bm.Range.Text = string.Format("{0:yyyy年MM月dd日}-{1:yyyy年MM月dd日}", st, ed);

            Word.Row row;
            Word.Cell cell;
            Word.Table tbl = doc.Tables[1];

            int iRow = 0;
            foreach (Question question in p)
            {
                iRow++;
                row = tbl.Rows.Add();

                cell = row.Cells[1];
                cell.Range.Text = Convert.ToString(iRow);

                cell = row.Cells[2];
                cell.Range.Text = string.Format("{0:yyyy年MM月dd日 HH:mm}", question.Time);

                cell = row.Cells[3];
                cell.Range.Text = question.Title;

                cell = row.Cells[4];
                cell.Range.Text = question.Name;

                cell = row.Cells[5];
                cell.Range.Text = string.Format("{0}-{1}-{2}", question.Country, question.Street, question.Village);


                StringBuilder sb1 = new StringBuilder();
                #region 获取指定的提问教师
                string ts = question.Teachers.Replace(',', ' ');
                var qts = from aT in db.Teacher
                          select aT;
                var pts = qts.Where(PredicateBuilder<Teacher>.CreatePredicate(new string[] { "ID" }, ts, "aT")).Select(aT => aT.Name);
                foreach (string n in pts)
                {
                    sb1.Append((sb1.Length == 0 ? "" : ",") + n);
                }
                #endregion
                cell = row.Cells[6];
                cell.Range.Text = sb1.ToString();


                #region 答复时间段
                var answers = question.Answer;

                if (answers.Count() == 0)
                {
                    cell = row.Cells[7];
                    cell.Range.Text = "";

                    cell = row.Cells[8];
                    cell.Range.Text = "";

                    cell = row.Cells[9];
                    cell.Range.Text = question.Description;
                }
                else
                {
                    DateTime limited = question.Time.AddDays(3);
                    DateTime created = answers.OrderBy(aA => aA.Time).Select(aA => aA.Time).First();

                    if (created.CompareTo(limited) <= 0)
                    {
                        cell = row.Cells[7];
                        cell.Range.Text = "是";

                        cell = row.Cells[8];
                        cell.Range.Text = "";

                        cell = row.Cells[9];
                        cell.Range.Text = "";
                    }
                    else
                    {
                        cell = row.Cells[7];
                        cell.Range.Text = "";

                        cell = row.Cells[8];
                        cell.Range.Text = "是";

                        cell = row.Cells[9];
                        cell.Range.Text = "";
                    }
                }

                #endregion
            }

            doc.Save();
            doc.Close(ref ms, ref ms, ref ms);

            doc = null;

            Response.Redirect(string.Format("~/Temps/{0}", file));
        }
        catch (Exception ee)
        {
            MessageBox.Message = ee.StackTrace;
        }
        finally
        {
            if (app != null)
            {
                app.Quit(ref ms, ref ms, ref ms);
                app = null;
            }
        }
    }
    protected void Export2_Click(object sender, EventArgs e)
    {
        DateTime st = DateTime.Parse(string.Format("{0}年{1}月{2}日", Year1.SelectedValue, Month1.SelectedValue, Day1.SelectedValue));
        DateTime ed = DateTime.Parse(string.Format("{0}年{1}月{2}日", Year2.SelectedValue, Month2.SelectedValue, Day2.SelectedValue));

        Word.Application app = null;
        Word.Document doc = null;

        object ms = Type.Missing;

        CmsDataContext db = new CmsDataContext();
        var q = from aQ in db.Question
                select aQ;

        try
        {
            string path = Toolkit.MappingPath(Toolkit.PathOfTemporary);
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            string file = Toolkit.NextUUID + ".doc";
            File.Copy(Toolkit.MappingPath(string.Format("{0}/{1}", Toolkit.PathOfReport, Toolkit.TemplateOfStatQuestionAll)), string.Format("{0}/{1}", path, file));

            app = new Word.Application();
            doc = app.Documents.Open(string.Format("{0}/{1}", path, file));

            Word.Bookmark bm = doc.Bookmarks["Time"];
            bm.Range.Text = string.Format("{0:yyyy年MM月dd日}", DateTime.Now);

            bm = doc.Bookmarks["Person"];
            bm.Range.Text = Toolkit.CurrentUserName;

            bm = doc.Bookmarks["During"];
            bm.Range.Text = string.Format("{0:yyyy年MM月dd日}-{1:yyyy年MM月dd日}", st, ed);

            Word.Row row;
            Word.Cell cell;
            Word.Table tbl = doc.Tables[1];

            int iRow = 0;

            XmlDocument xmldoc = new XmlDocument();
            xmldoc.Load(Toolkit.GetRealDataFilePath("Department.xml"));

            XmlElement root = xmldoc.DocumentElement;

            foreach (XmlNode node in root.SelectNodes("/Root/District"))
            {
                string district = node.Attributes["name"].Value.ToString();
                var p = q.Where(aQ => aQ.Country == district);

                iRow++;
                row = tbl.Rows.Add();

                cell = row.Cells[1];
                cell.Range.Text = Convert.ToString(iRow);

                cell = row.Cells[2];
                cell.Range.Text = district;

                cell = row.Cells[3];
                cell.Range.Text = Convert.ToString(p.Count());


                int[] c = { 0, 0, 0 };
                foreach (var qt in p)
                {
                    if (qt.Answer.Count() == 0)
                    {
                        c[2]++;
                    }
                    else
                    {
                        DateTime limited = qt.Time.AddDays(3);
                        DateTime created = qt.Answer.OrderBy(aA => aA.Time).Select(aA => aA.Time).First();

                        if (created.CompareTo(limited) <= 0)
                        {
                            c[0]++;
                        }
                        else
                        {
                            c[1]++;
                        }
                    }
                }

                cell = row.Cells[4];
                cell.Range.Text = Convert.ToString(c[0]);

                cell = row.Cells[5];
                cell.Range.Text = Convert.ToString(c[1]);

                cell = row.Cells[6];
                cell.Range.Text = Convert.ToString(c[2]);
            }


            doc.Save();
            doc.Close(ref ms, ref ms, ref ms);

            doc = null;

            Response.Redirect(string.Format("~/Temps/{0}", file));
        }
        catch (Exception ee)
        {
            MessageBox.Message = ee.StackTrace;
        }
        finally
        {
            if (app != null)
            {
                app.Quit(ref ms, ref ms, ref ms);
                app = null;
            }
        }
    }
}